import requests,re,os

filename = 'music\\'

if not os.path.exists(filename):
    os.mkdir(filename)

urlwanyiyun='https://music.163.com/discover/toplist?id=19723756'

myheaders ={
    'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36 Edg/103.0.1264.37'
}
html = requests.get(url=urlwanyiyun,headers=myheaders)#访问网址得到html
name_data = re.findall('<li><a href="/song\?id=(\d+)">(.*?)</a></li>',html.text)#使用正则表达式取出id，和歌曲名

for id, name in name_data:
    mp3_url = f'http://music.163.com/song/media/outer/url?id={id}.mp3'
    mp3_content = requests.get(url=mp3_url, headers=myheaders).content#下载歌曲mp3文件
    with open(filename+'music_list.txt',mode='a', encoding='utf8')as fl:        
        fl.write(name+'         歌曲id:'+id+'\n')#将歌曲名和id储存在txt中
    with open(filename+name+'.mp3',mode='wb')as f:#保存歌曲mp3文件
        f.write(mp3_content)
    